package entity

import (
	"errors"
	"fmt"
	"time"

	"github.com/jinzhu/gorm"
	"shqsoft.cn/pasnj/base"
	"shqsoft.cn/pasnj/workflow"
	"shqsoft.cn/pasnj/workflow/entity"
)

//COMP_DFGZFlowApp 附件
type COMP_DFGZFlowApp struct {
	ID         int       `gorm:"AUTO_INCREMENT;primary_key;column:ID"`
	CUID       int       `gorm:"column:CUID"`
	CUNM       string    `gorm:"column:CUNM"`
	DWBH       string    `gorm:"column:DWBH"`
	DGKHH      string    `gorm:"column:DGKHH"`
	DSDT       time.Time `gorm:"column:DSDT"`
	EMNO1      string    `gorm:"column:EMNO1"`
	EMID1      int       `gorm:"column:EMID1"`
	EMNM1      string    `gorm:"-" json:"emnm1"`
	DSVL1      float64   `gorm:"column:DSVL1"`
	EMNO2      string    `gorm:"column:EMNO2"`
	EMNM2      string    `gorm:"-" json:"emnm2"`
	EMID2      int       `gorm:"column:EMID2"`
	DSVL2      float64   `gorm:"column:DSVL2"`
	EMNO3      string    `gorm:"column:EMNO3"`
	EMNM3      string    `gorm:"-" json:"emnm3"`
	EMID3      int       `gorm:"column:EMID3"`
	DSVL3      float64   `gorm:"column:DSVL3"`
	EMNO4      string    `gorm:"column:EMNO4"`
	EMNM4      string    `gorm:"-" json:"emnm4"`
	EMID4      int       `gorm:"column:EMID4"`
	DSVL4      float64   `gorm:"column:DSVL4"`
	EMNO5      string    `gorm:"column:EMNO5"`
	EMNM5      string    `gorm:"-" json:"emnm5"`
	EMID5      int       `gorm:"column:EMID5"`
	DSVL5      float64   `gorm:"column:DSVL5"`
	UID        int       `gorm:"column:UID"`
	FRID       int       `gorm:"column:FRID"`
	STEP       int       `gorm:"-" json:"step"`
	Progress   float64   `gorm:"-" json:"progress"`
	StepName   string    `gorm:"-" json:"stepName"`
	Status     string    `gorm:"-" json:"status"`
	THSM       string    `gorm:"column:THSM"`
	SQR        string    `gorm:"column:SQR"`
	SQR2       string    `gorm:"column:SQR2"`
	SQR3       string    `gorm:"column:SQR3"`
	SQR4       string    `gorm:"column:SQR4"`
	SQR5       string    `gorm:"column:SQR5"`
	CREATETIME time.Time `gorm:"column:CREATETIME"`
	UPDATETIME time.Time `gorm:"column:UPDATETIME"`
}

//TableName COMP_DFGZFlowApp表名
func (COMP_DFGZFlowApp) TableName() string {
	return "T_COMP_DFGZ_RD"
}

//BeforeSave 保存前的触发器
func (i *COMP_DFGZFlowApp) BeforeSave(tx *gorm.DB) (err error) {
	var emid1, emid2, emid3 int
	sqlEx := "select ID,SysUserName from T_SysUser where SysUserID=?"
	row := tx.Raw(sqlEx, i.EMNO1).Row()
	row.Scan(&emid1, &i.SQR)
	i.EMID1 = emid1
	if i.UID == 0 {
		i.UID = i.EMID1
	}
	if i.DSVL2 > 0 {
		row = tx.Raw(sqlEx, i.EMNO2).Row()
		row.Scan(&emid2, &i.SQR2)
		if emid2 == 0 {
			return fmt.Errorf("员工号2:%s在系统中没有找到！", i.EMNO2)
		}
		i.EMID2 = emid2
	}
	if i.DSVL3 > 0 {
		row = tx.Raw(sqlEx, i.EMNO3).Row()
		row.Scan(&emid3, &i.SQR3)
		if emid3 == 0 {
			return fmt.Errorf("员工号3:%s在系统中没有找到！", i.EMNO3)
		}
		i.EMID3 = emid3
	}
	sum := i.DSVL1 + i.DSVL2 + i.DSVL3 + i.DSVL4 + i.DSVL5
	if sum != 100 {
		return errors.New("占比之和必须为100！")
	}
	if i.DSVL1 == 0 {
		return errors.New("员工号1占比不能为0！")
	}
	var count int
	sqlEx = "select count(a.ID) from T_COMP_DFGZ_RD a inner join T_FLOW_RUN b on a.FRID=b.ID where b.STATE=0 and a.DWBH=?"
	row = tx.Raw(sqlEx, i.DWBH).Row()
	row.Scan(&count)
	if count > 0 {
		return fmt.Errorf("单位编号/协议编号:【%s】已经在申请中，不能重复申请！", i.CUNM)
	}
	if i.ID > 0 {
		row := base.DB.Model(COMP_DFGZFlowApp{}).Where("ID=?", i.ID).Select("FRID").Row()
		row.Scan(&i.FRID)
	}
	wfid := 32
	runid, err := workflow.Create(wfid, i.UID, tx)
	if err != nil {
		return err
	}
	i.FRID = runid

	i.CREATETIME = time.Now()
	i.UPDATETIME = time.Now()
	return
}

// AfterFind 查询后触发器
func (i *COMP_DFGZFlowApp) AfterFind(tx *gorm.DB) (err error) {
	sqlEx := "select SysUserName from T_SysUser where ID = ?"
	row := tx.Raw(sqlEx, i.EMID1).Row()
	row.Scan(&i.EMNM1)
	if i.DSVL2 > 0 {
		row := tx.Raw(sqlEx, i.EMID2).Row()
		row.Scan(&i.EMNM2)
	}
	if i.DSVL3 > 0 {
		row := tx.Raw(sqlEx, i.EMID3).Row()
		row.Scan(&i.EMNM3)
	}
	if i.DSVL4 > 0 {
		row := tx.Raw(sqlEx, i.EMID4).Row()
		row.Scan(&i.EMNM4)
	}
	if i.DSVL5 > 0 {
		row := tx.Raw(sqlEx, i.EMID5).Row()
		row.Scan(&i.EMNM5)
	}

	if i.FRID == 0 {
		i.Status = "exception"
		i.StepName = "校验错误"
		return
	}
	run := entity.FlowRun{}
	if err = tx.Find(&run, i.FRID).Error; err != nil {
		tx.Rollback()
		return
	}
	wf := workflow.GetWorkFlow(run.WFID)
	if wf == nil {
		return fmt.Errorf("指定的流程ID:%d在流程配置中不存在！", run.WFID)
	}
	act := wf.GetAction(run.Step)
	if act == nil {
		return fmt.Errorf("指定的stepID:%d在流程%s配置中不存在！", run.Step, wf.Name)
	}
	count := len(wf.Actions)
	i.STEP = run.Step
	i.StepName = "审批中"
	if i.STEP == 1 {
		i.StepName = "申请中"
	}
	i.Progress = float64(act.Step*100) / float64(count)
	if i.Progress >= 100 && run.State == "0" {
		i.Progress = 95
	}
	i.Status = ""
	if run.State == "0" {
		i.Status = "active"
	} else if run.State == "2" {
		i.StepName = "已中止"
		i.Status = "exception"
	} else {
		i.StepName = "已完成"
		i.Status = "success"
	}
	return
}

func (i *COMP_DFGZFlowApp) AfterDelete(tx *gorm.DB) (err error) {

	return nil
}

//FilesEF 获取实体类对象"EmplYgdd";
func COMP_DFGZFlowAppEF() base.EntityFunc {
	return func() interface{} {
		entity := COMP_DFGZFlowApp{}
		return &entity
	}
}

//COMP_DFGZFlowAppESF 获取实体类对象数组
func COMP_DFGZFlowAppESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []COMP_DFGZFlowApp
		return &entities
	}
}
func init() {
	dao := base.NewDefaultDao(COMP_DFGZFlowAppEF(), COMP_DFGZFlowAppESF(), nil)
	filter := base.WorkFolowFilter{
		FilterColName: "FRID",
	}
	filter.SetAdditional("wfid", "32")
	dao.Fileter = &filter
	base.DaoPoolObj.Put("COMP_DFGZFlowApp", dao)
}
